from flask import Blueprint, jsonify, request
import pdfplumber
import re, os
from datetime import datetime
from parseReport.database import db
from parseReport.Config import Config
from parseReport.AlipayInfo import PayInfo
from flask_cors import CORS, cross_origin

wx_info_bp = Blueprint('wxinfo', __name__)

@cross_origin
@wx_info_bp.route('/getData_wxPdf', methods=['POST'])
def getData_wxPdf():
    # 设置上传文件的目录（临时目录）
    UPLOAD_FOLDER = Config.UPLOAD_FOLDER
    os.makedirs(UPLOAD_FOLDER, exist_ok=True)

    # 检查请求中是否有文件
    if 'file' not in request.files:
        return jsonify({'data': '', 'msg': '没有文件上传', 'status': 400})

    if 'userId' not in request.values.keys():
        return jsonify({'data': '', 'msg': '上传文件时，未检测到用户id', 'status': 400})

    userId = request.values.get('userId')

    file = request.files['file']

    # 检查文件是否有效
    if file.filename == '':
        return jsonify({'data': '', 'msg': '没有选择文件', 'status': 400})

    if file and allowed_file(file.filename):  # 确保有一个 allowed_file 函数

        # pdf_file = '/Users/wubing/Desktop/pdfData/支付宝副本.pdf'
        try:
            # 保存上传的文件
            pdf_file_path = os.path.join(UPLOAD_FOLDER, file.filename)
            file.save(pdf_file_path)
            data_list = getDataFromWxPdf(pdf_file_path, userId)
            for data in data_list:
                db.session.add(data)
                db.session.commit()
            return jsonify({
                'data': '',
                'message': '成功导入' + len(data_list).__str__() + '条数据',
                'status': 200
            })
        except Exception as e:
            print(str(e))
            return jsonify({'data': '', 'msg': '导入数据失败，失败原因为:' + str(e), 'status': 500})


def allowed_file(filename):
    ALLOWED_EXTENSIONS = {'pdf'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def getDataFromWxPdf(pdf_file: str, userId: str):
    # pdf_file = '/Users/wubing/Desktop/pdfData/微信支付副本.pdf'
    ##使用正则提取文本中的用户信息
    all_pages_content = ""
    with pdfplumber.open(pdf_file) as pdf:
        for page in pdf.pages:
            all_pages_content += page.extract_text()
    # 使用正则表达式匹配编号
    ##编号
    number = ''
    ##姓名
    name = ''
    ##证件号码
    identificationNumber = ''
    ##支付宝账号信息
    wx_num = ''

    pattern = r'编号：(\d+)'
    match = re.search(pattern, all_pages_content)
    if match:
        number = match.group(1)

    pattern = r'兹证明：([\u4e00-\u9fa5]+)\('
    match = re.search(pattern, all_pages_content)
    if match:
        name = match.group(1)

    pattern = r'居民身份证：(\d{6}\d{4}\d{2}\d{2}\d{3}\d{1})'
    match = re.search(pattern, all_pages_content)
    if match:
        identificationNumber = match.group(1)

    pattern = r'微信号：\s*(.*?)\s*中的'
    match = re.search(pattern, all_pages_content)
    if match:
        account = match.group(1)

    with pdfplumber.open(pdf_file) as pdf:
        tables = []
        # 遍历所有的页面
        for page in pdf.pages:
            tables.extend(page.extract_tables())

    result_list = []

    for index, table_tmp in enumerate(tables):
        if index == 0:
            for index_data, table_data in enumerate(table_tmp):
                if index_data > 2:
                    object = get_object(table_data, number, name, identificationNumber, account, userId)
                    result_list.append(object)
        else:
            for index_data, table_data in enumerate(table_tmp):
                object = get_object(table_data, number, name, identificationNumber, account, userId)
                result_list.append(object)
    return result_list


def get_object(table_data, number, name, identificationNumber, account, userId) -> PayInfo:
    transactionNum = table_data[0].replace('\n', '')
    tradeTime = table_data[1].replace('\n', ' ')
    tradeType = table_data[2].replace('\n', '')
    type = table_data[3].replace('\n', '')
    payWay = table_data[4].replace('\n', '')
    price = table_data[5].replace('\n', '')
    trade = table_data[6].replace('\n', '')
    saleOrderNum = table_data[7].replace('\n', ' ')

    object = PayInfo()
    object.transactionNum = transactionNum
    object.tradeTime = tradeTime
    object.tradeType = tradeType
    object.type = type
    object.payWay = payWay
    object.price = price
    object.trade = trade
    object.saleOrderNum = saleOrderNum
    object.number = number
    object.name = name
    object.identificationNumber = identificationNumber
    object.account = account
    object.origin = 'wx_report'
    object.platform = '微信'
    object.userId = userId
    return object
